package sch.guo.crmsys.controller.cop;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import sch.guo.crmsys.base.ResultUtil;
import sch.guo.crmsys.base.dto.ResultDTO;
import sch.guo.crmsys.service.cop.CopDepartmentService;
import sch.guo.crmsys.entity.cop.CopDepartment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/copDepartment")
public class CopDepartmentController {

    @Autowired
    private CopDepartmentService copDepartmentService;

    @PostMapping
    @ApiOperation(value = "插入")
    public ResultDTO insertOne(CopDepartment copDepartment) throws Exception {
        copDepartmentService.save(copDepartment);
        return ResultUtil.Success(copDepartment);
    }

    @PutMapping
    @ApiOperation(value = "按ID修改")
    public ResultDTO updateById(@RequestBody CopDepartment copDepartment) throws Exception {
        copDepartmentService.updateById(copDepartment);
        return ResultUtil.Success();
    }

    @DeleteMapping("/{id:\\d+}")
    @ApiOperation("按iD删除")
    public ResultDTO deleteById(@PathVariable Long id) throws Exception {
        copDepartmentService.removeById((long) id);
        return ResultUtil.Success();
    }


    @GetMapping("/list")
    @ApiOperation("条件查询、分页返回")
    public ResultDTO selectEntityPage(@RequestParam(value = "page", defaultValue = "0") int pageNum,
                                      @RequestParam(value = "limit", defaultValue = "8") int pageSize)throws Exception{
        IPage<CopDepartment> page = copDepartmentService.page(new Page<CopDepartment>(pageNum, pageSize));
        List<CopDepartment> departments = page.getRecords();
        for (CopDepartment department : departments) {
            for (CopDepartment copDepartment : departments) {
                if (department.getDepartmentParent() == copDepartment.getDepartmentId()) {
                    department.setDepartmentParentName(copDepartment.getDepartmentName());
                }
            }
        }
        int count = (int) page.getTotal();
        return ResultUtil.Success(departments,count);
    }

    @GetMapping("/{id:\\d+}")
    @ApiOperation("ID查询")
    public ResultDTO selectEntityPage(@PathVariable Long id)throws Exception{
        return ResultUtil.Success(Arrays.asList(copDepartmentService.getById(id)));
    }

}
